package com.gsi.webstore.platform.storefront.pipelet;

import java.util.Iterator;

import com.intershop.beehive.core.capi.domain.Domain;
import com.intershop.beehive.core.capi.naming.NamingMgr;
import com.intershop.beehive.core.capi.pipeline.Pipelet;
import com.intershop.beehive.core.capi.pipeline.PipeletExecutionException;
import com.intershop.beehive.core.capi.pipeline.PipelineDictionary;
import com.intershop.beehive.core.capi.pipeline.PipelineInitializationException;
import com.intershop.component.captcha.capi.CaptchaService;
import com.intershop.component.service.capi.ServiceMgr;

/**
 * 
 */
public class IsCaptchaServiceEnabled extends Pipelet
{
    /**
     * Constant used to access the pipeline dictionary with key 'ChannelDomain'
     */
    public static final String DN_CHANNEL_DOMAIN = "ChannelDomain";
    /**
     * Constant used to access the pipeline dictionary with key 'DisplayCaptcha'
     */
    public static final String DN_DISPLAY_CAPTCHA = "DisplayCaptcha";

    private ServiceMgr serviceMgr;
    
    @Override
    public void init() throws PipelineInitializationException
    {
        super.init();
        serviceMgr = NamingMgr.getManager(ServiceMgr.class);
    }
    
    /**
     * The pipelet's execute method is called whenever the pipelets gets
     * executed in the context of a pipeline and a request. The pipeline
     * dictionary valid for the currently executing thread is provided as
     * a parameter.
     *  
     * @param   dict The pipeline dictionary to be used.
     * @throws  PipeletExecutionException
     *          Thrown in case of severe errors that make the pipelet execute
     *          impossible (e.g. missing required input data).
     */
    public int execute(PipelineDictionary dict) throws PipeletExecutionException {        
        // lookup 'ChannelDomain' in pipeline dictionary
        Domain channelDomain = (Domain)dict.get(DN_CHANNEL_DOMAIN);
        if (null == channelDomain)
        {
            throw new PipeletExecutionException(
                            "Mandatory input parameter 'ChannelDomain' not available in pipeline dictionary.");
        
        }

        //find captcha service implementations for the current domain
        Iterator<CaptchaService> iter = serviceMgr.getServiceImplementations(channelDomain, CaptchaService.class);
        
        //check if service available
        while (iter.hasNext())
        {
            dict.put(DN_DISPLAY_CAPTCHA, true); 
            break;
        }  
        return PIPELET_NEXT;
    }
}